<template>
  <div class="study-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar title="学习中心" fixed placeholder>
      <template #right>
        <van-icon name="search" @click="handleSearch" />
        <van-icon name="bell-o" @click="handleNotification" class="ml-4" />
      </template>
    </van-nav-bar>

    <!-- 主内容区域 -->
    <div class="study-content">
      <!-- 搜索和筛选区域 -->
      <div class="search-filter-section">
        <div class="search-container">
          <van-search
            v-model="searchKeyword"
            placeholder="搜索课程或内容..."
            shape="round"
            @search="onSearch"
            @clear="onClear"
            class="search-input"
          />
        </div>
        <van-button 
          icon="filter-o" 
          type="default" 
          size="large" 
          round 
          @click="showFilter = true"
          class="filter-btn"
        />
      </div>

      <!-- 学习进度区域 -->
      <div class="progress-section">
        <div class="section-header">
          <h2 class="section-title">我的学习进度</h2>
          <van-button
            type="primary"
            size="small"
            round
            @click="goToProgressDetail"
            class="detail-btn"
          >
            查看详情
          </van-button>
        </div>
        <div class="progress-list">
          <div
            v-for="progress in learningProgress"
            :key="progress.id"
            class="progress-item"
          >
            <div class="progress-info">
              <span class="course-name">{{ progress.courseName }}</span>
              <span class="progress-percent">{{ progress.percentage }}%</span>
            </div>
            <van-progress
              :percentage="progress.percentage"
              :color="progress.color"
              stroke-width="0.8vw"
              track-color="#f5f7fa"
            />
          </div>
        </div>
      </div>

      <!-- 推荐课程列表 -->
      <div class="courses-section">
        <h2 class="section-title">推荐课程</h2>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <van-loading size="24px" color="#1989fa">加载中...</van-loading>
        </div>

        <!-- 课程列表 -->
        <div v-else-if="recommendedCourses.length > 0" class="courses-list">
          <div
            v-for="course in recommendedCourses"
            :key="course.id"
            class="course-card"
            @click="goToCourse(course)"
          >
            <div class="course-image">
              <van-image
                :src="course.cover"
                fit="cover"
                :alt="course.title"
                loading-icon="photo"
                error-icon="photo-fail"
              />
            </div>
            <div class="course-content">
              <h3 class="course-title">{{ course.title }}</h3>
              <p class="course-description">{{ course.description }}</p>
              <div class="course-meta">
                <div class="rating">
                  <van-icon name="star" color="#ffd21e" />
                  <span>{{ course.rating }}</span>
                </div>
                <div class="students">
                  <span>{{ course.student_count }}人学习</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <van-empty
          v-else
          image="search"
          description="暂无推荐课程"
          class="empty-state"
        >
          <van-button
            round
            type="primary"
            class="bottom-button"
            @click="loadStudyData"
          >
            重新加载
          </van-button>
        </van-empty>
      </div>
    </div>

    <!-- 筛选弹窗 -->
    <van-popup v-model:show="showFilter" position="bottom" round>
      <div class="filter-popup">
        <div class="filter-header">
          <h3>筛选条件</h3>
          <van-button type="primary" size="small" @click="resetFilter">重置</van-button>
        </div>
        
        <div class="filter-content">
          <div class="filter-group">
            <h4>课程分类</h4>
            <van-checkbox-group v-model="filterOptions.categories">
              <van-checkbox
                v-for="category in categories"
                :key="category.id"
                :name="category.id.toString()"
              >
                {{ category.name }}
              </van-checkbox>
            </van-checkbox-group>
          </div>

          <div class="filter-group">
            <h4>难度级别</h4>
            <van-radio-group v-model="filterOptions.difficulty">
              <van-radio 
                v-for="level in difficultyLevels" 
                :key="level.value"
                :name="level.value"
              >
                {{ level.label }}
              </van-radio>
            </van-radio-group>
          </div>
        </div>

        <div class="filter-footer">
          <van-button block type="primary" @click="applyFilter">确定</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import { StudyService } from '@/api/services';
import { getCourseCategories, getRecommendedCourses } from '@/api/index';
import type { Category, Course } from '@/api/index';
import { AuthUtils, TokenManager, UserManager } from '@/utils/auth';
import { ApiTestUtil } from '@/utils/api-test';

const router = useRouter();

// 开发环境检测
const isDev = import.meta.env.DEV;

// 响应式数据
const searchKeyword = ref('');
const showFilter = ref(false);
const loading = ref(false);

// 学习数据
const categories = ref<Category[]>([]);
const recommendedCourses = ref<Course[]>([]);
const learningProgress = ref<any[]>([]);

// 默认数据
const defaultCategories: Category[] = [
  { id: 1, name: '发音基础', icon: 'volume-o', color: '#1989fa', courseCount: 15, sort: 1 },
  { id: 2, name: '日常会话', icon: 'chat-o', color: '#07c160', courseCount: 12, sort: 2 },
  { id: 3, name: '朗读技巧', icon: 'play-circle-o', color: '#ff9800', courseCount: 8, sort: 3 },
  { id: 4, name: '汉字书写', icon: 'edit', color: '#9c27b0', courseCount: 6, sort: 4 }
];

const defaultCourses: Course[] = [
  {
    id: 1,
    title: '普通话声调精讲',
    description: '深入学习普通话四声及变调，告别"塑料普通话"。',
    cover: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/9bbeb5082d711bf94a7da332f15098d7.png',
    rating: 4.9,
    studentCount: 1500,
    categoryId: 1,
    difficulty: 'intermediate',
    duration: 7200,
    instructor: '张老师',
    price: 0,
    originalPrice: 99,
    isRecommended: true,
    tags: ['发音', '声调'],
    createdAt: '2024-01-01',
    updatedAt: '2024-01-01'
  },
  {
    id: 2,
    title: '日常会话300句',
    description: '掌握日常交流必备短语，轻松应对生活场景。',
    cover: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/a696f971980016d0ab967959aad08f59.png',
    rating: 4.7,
    studentCount: 1000,
    categoryId: 2,
    difficulty: 'beginner',
    duration: 5400,
    instructor: '李老师',
    price: 0,
    originalPrice: 129,
    isRecommended: true,
    tags: ['会话', '日常'],
    createdAt: '2024-01-01',
    updatedAt: '2024-01-01'
  },
  {
    id: 3,
    title: '中国文化与历史',
    description: '了解中国传统文化，提升语言学习的深度。',
    cover: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/91ab48b1728415340033baff91d92a03.png',
    rating: 4.6,
    studentCount: 700,
    categoryId: 3,
    difficulty: 'advanced',
    duration: 9000,
    instructor: '王老师',
    price: 0,
    originalPrice: 199,
    isRecommended: true,
    tags: ['文化', '历史'],
    createdAt: '2024-01-01',
    updatedAt: '2024-01-01'
  }
];

// 筛选选项
const filterOptions = ref({
  categories: [] as string[],
  difficulty: ''
});

// 难度级别
const difficultyLevels = ref([
  { label: '全部', value: '' },
  { label: '初级', value: 'easy' },
  { label: '中级', value: 'medium' },
  { label: '高级', value: 'hard' }
]);

// 加载学习中心数据
const loadStudyData = async () => {
  try {
    loading.value = true;
    console.log('开始加载学习中心数据...');

    // 使用新的API服务分别获取数据
    const [categoriesResult, coursesResult] = await Promise.all([
      StudyService.getCategories(),
      StudyService.getRecommendedCourses({ page: 1, limit: 20 })
    ]);

    console.log('分类API返回:', categoriesResult);
    console.log('课程API返回:', coursesResult);

    // 处理分类数据
    if (categoriesResult && categoriesResult.data && Array.isArray(categoriesResult.data)) {
      categories.value = categoriesResult.data;
      console.log('✅ 分类数据加载成功，数量:', categories.value.length);
    } else {
      categories.value = [];
      console.log('⚠️ 分类数据为空或格式错误');
    }

    // 处理课程数据 - 根据后端实际返回的数据结构
    if (coursesResult && coursesResult.data && coursesResult.data.list && Array.isArray(coursesResult.data.list)) {
      recommendedCourses.value = coursesResult.data.list;
      console.log('✅ 课程数据加载成功，数量:', recommendedCourses.value.length);
      console.log('课程数据详情:', coursesResult.data.list);

      // 调试：检查第一个课程的数据结构
      if (coursesResult.data.list.length > 0) {
        const firstCourse = coursesResult.data.list[0];
        console.log('第一个课程数据结构:', {
          id: firstCourse.id,
          title: firstCourse.title,
          description: firstCourse.description,
          cover: firstCourse.cover,
          rating: firstCourse.rating,
          student_count: firstCourse.student_count,
          category: firstCourse.category
        });
      }
    } else {
      recommendedCourses.value = [];
      console.log('⚠️ 课程数据为空或格式错误，实际数据结构:', coursesResult);
    }

    console.log('学习数据加载完成');
  } catch (error) {
    console.error('加载学习数据失败:', error);
    showToast('加载数据失败');

    // 错误时清空数据，显示空状态
    categories.value = [];
    recommendedCourses.value = [];
  } finally {
    loading.value = false;
  }
};

// 方法
const handleSearch = () => {
  showToast('搜索功能');
};

const handleNotification = () => {
  showToast('通知功能');
};

// 测试API连接
const testApiConnection = async () => {
  await ApiTestUtil.testConnectivity();
};

// 运行所有API测试
const runAllApiTests = async () => {
  await ApiTestUtil.runAllTests();
};

const testAPI = async () => {
  try {
    console.log('🚀 开始测试API连接...');
    console.log('📡 后端地址: http://10.4.64.155:3000');
    console.log('🔗 代理配置: /api -> http://10.4.64.155:3000');
    showToast('正在测试API连接...');

    // 测试获取课程分类
    console.log('📚 测试获取课程分类...');
    const categoriesResult = await getCourseCategories();
    console.log('✅ 分类API测试结果:', categoriesResult);

    // 测试获取推荐课程
    console.log('🎯 测试获取推荐课程...');
    const coursesResult = await getRecommendedCourses({ page: 1, limit: 10 });
    console.log('✅ 课程API测试结果:', coursesResult);

    // 显示成功信息
    console.log('🎉 API连接测试完成！');
    showToast('API连接测试成功！请查看控制台详细信息');

    // 如果有数据，更新界面
    if (categoriesResult && Array.isArray(categoriesResult)) {
      console.log(`📊 获取到 ${categoriesResult.length} 个分类`);
    }
    if (coursesResult && (coursesResult as any).list && Array.isArray((coursesResult as any).list)) {
      console.log(`📊 获取到 ${(coursesResult as any).list.length} 个推荐课程`);
    }

  } catch (error: any) {
    console.error('❌ API测试失败:', error);
    console.error('🔍 错误详情:', {
      message: error?.message,
      status: error?.response?.status,
      statusText: error?.response?.statusText,
      data: error?.response?.data
    });
    showToast(`API测试失败: ${error?.message || error}`);
  }
};

const onSearch = async (value: string) => {
  if (!value.trim()) {
    showToast('请输入搜索关键词');
    return;
  }

  try {
    loading.value = true;
    console.log('搜索课程:', value);

    const result = await StudyService.searchCourses(value, {
      category: filterOptions.value.categories.join(','),
      difficulty: filterOptions.value.difficulty
    });

    if (result && result.list.length > 0) {
      recommendedCourses.value = result.list;
      showToast(`找到 ${result.total} 个相关课程`);
    } else {
      showToast('未找到相关课程');
      recommendedCourses.value = [];
    }
  } catch (error) {
    console.error('搜索失败:', error);
    showToast('搜索失败，请重试');
  } finally {
    loading.value = false;
  }
};

const onClear = () => {
  searchKeyword.value = '';
  // 清空搜索时重新加载推荐课程
  loadStudyData();
};

const goToCourse = (course: any) => {
  console.log('进入课程:', course);
  // 跳转到课程详情页
  router.push(`/course/${course.id}`);
};

// 跳转到学习进度详情页
const goToProgressDetail = () => {
  router.push('/study/progress');
};

const resetFilter = () => {
  filterOptions.value.categories = [];
  filterOptions.value.difficulty = '';
};

const applyFilter = async () => {
  try {
    loading.value = true;
    showFilter.value = false;

    console.log('应用筛选:', filterOptions.value);

    // 如果有搜索关键词，使用搜索API；否则获取推荐课程
    if (searchKeyword.value.trim()) {
      const result = await StudyService.searchCourses(searchKeyword.value, {
        category: filterOptions.value.categories.join(','),
        difficulty: filterOptions.value.difficulty
      });

      if (result && result.list.length > 0) {
        recommendedCourses.value = result.list;
        showToast(`筛选后找到 ${result.total} 个课程`);
      } else {
        recommendedCourses.value = [];
        showToast('筛选后未找到相关课程');
      }
    } else {
      // 重新加载数据（这里可以后续优化为带筛选参数的API调用）
      await loadStudyData();
      showToast('筛选已应用');
    }
  } catch (error) {
    console.error('筛选失败:', error);
    showToast('筛选失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 测试Token功能
const testToken = () => {
  try {
    console.log('🔐 Token测试开始...');

    // 检查认证状态
    const isAuthenticated = AuthUtils.isAuthenticated();
    const hasToken = TokenManager.hasToken();
    const isValidToken = TokenManager.isValidToken();
    const token = TokenManager.getToken();
    const userInfo = UserManager.getUserInfo();

    console.log('📊 认证状态检查:', {
      isAuthenticated,
      hasToken,
      isValidToken,
      tokenLength: token ? token.length : 0,
      userInfo
    });

    // 解析Token payload
    if (token) {
      const payload = TokenManager.parseTokenPayload();
      console.log('🔍 Token Payload:', payload);

      // 检查是否即将过期
      const isExpiringSoon = TokenManager.isTokenExpiringSoon();
      console.log('⏰ Token即将过期:', isExpiringSoon);
    }

    // 获取认证头
    const authHeader = AuthUtils.getAuthHeader();
    console.log('📋 认证头:', authHeader);

    // 显示结果
    if (isAuthenticated) {
      showToast('✅ Token有效，用户已认证');
    } else if (hasToken) {
      showToast('⚠️ Token存在但无效');
    } else {
      showToast('❌ 未找到Token');
    }

  } catch (error) {
    console.error('❌ Token测试失败:', error);
    showToast('Token测试失败');
  }
};

// 设置测试Token
const setTestToken = () => {
  try {
    // 创建一个测试用的JWT token
    const header = { alg: 'HS256', typ: 'JWT' };
    const payload = {
      sub: 'test-user-123',
      username: 'testuser',
      nickname: '测试用户',
      role: 'user',
      permissions: ['read', 'write'],
      iat: Math.floor(Date.now() / 1000),
      exp: Math.floor(Date.now() / 1000) + (24 * 60 * 60) // 24小时后过期
    };
    const signature = 'test-signature';

    // 简单的base64编码（仅用于测试）
    const testToken = `${btoa(JSON.stringify(header))}.${btoa(JSON.stringify(payload))}.${signature}`;

    // 创建测试用户信息
    const testUserInfo = {
      id: 'test-user-123',
      username: 'testuser',
      nickname: '测试用户',
      avatar: '',
      email: 'test@example.com',
      phone: '13800138000',
      role: 'user',
      permissions: ['read', 'write'],
      lastLoginTime: new Date().toISOString()
    };

    // 模拟登录响应
    const loginResponse = {
      token: testToken,
      userInfo: testUserInfo,
      expiresIn: 24 * 60 * 60 // 24小时
    };

    // 使用AuthUtils处理登录成功
    AuthUtils.handleLoginSuccess(loginResponse);

    console.log('🎭 测试Token已设置:', {
      token: testToken.substring(0, 50) + '...',
      userInfo: testUserInfo
    });

    showToast('✅ 测试Token已设置');

  } catch (error) {
    console.error('❌ 设置测试Token失败:', error);
    showToast('设置测试Token失败');
  }
};

// 清除Token（测试路由重定向）
const clearToken = () => {
  try {
    console.log('🗑️ 清除Token开始...');

    // 使用AuthUtils处理登出
    AuthUtils.handleLogout();

    console.log('✅ Token已清除');
    showToast('Token已清除，即将重定向到登录页');

    // 延迟一下让用户看到提示，然后尝试访问当前页面触发重定向
    setTimeout(() => {
      // 刷新当前页面，触发路由守卫检查
      router.go(0);
    }, 1500);

  } catch (error) {
    console.error('❌ 清除Token失败:', error);
    showToast('清除Token失败');
  }
};

// 页面初始化
onMounted(() => {
  loadStudyData();
});
</script>

<style lang="scss" scoped>
.study-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.study-content {
  padding: 4vw;
  padding-bottom: 20vw; // 为底部导航留空间
}

// 搜索筛选区域
.search-filter-section {
  display: flex;
  align-items: center;
  gap: 2.67vw;
  margin-bottom: 6.4vw;

  .search-container {
    flex: 1;
  }

  .search-input { 
    background-color: #f5f7fa;

    :deep(.van-search) {
      background-color: #f7f8fa;
      padding: 0;
    }
    
    :deep(.van-search__content) {
      background-color: #FFFFFF;
      border-radius: 3vw;
      border: 1px solid #ebedf0;
    }
    
    :deep(.van-field__control) {
      background-color: #FFFFFF;
    }
  }

  .filter-btn {
    width: 12vw;
    height: 12vw;
    border-radius: 50%;
    background: white;
    border: 1px solid #ebedf0;
  }
}

// 学习进度区域
.progress-section {
  background: white;
  border-radius: 2.67vw;
  padding: 5.33vw;
  margin-bottom: 6.4vw;
  box-shadow: 0 0.53vw 2.67vw rgba(0, 0, 0, 0.05);

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 4vw;
  }

  .section-title {
    font-size: 4.8vw;
    font-weight: 600;
    color: #323233;
    margin: 0;
  }

  .detail-btn {
    font-size: 3.2vw;
    padding: 1.6vw 3.2vw;
    height: auto;
    line-height: 1.2;
  }

  .progress-list {
    .progress-item {
      margin-bottom: 4vw;

      &:last-child {
        margin-bottom: 0;
      }

      .progress-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 2.67vw;

        .course-name {
          font-size: 3.73vw;
          color: #646566;
        }

        .progress-percent {
          font-size: 3.73vw;
          font-weight: 600;
          color: #1989fa;
        }
      }
    }
  }
}

// 课程列表区域
.courses-section {
  .section-title {
    font-size: 4.8vw;
    font-weight: 600;
    color: #323233;
    margin-bottom: 4vw;
  }

  .loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 8vw 0;
    color: #969799;
  }

  .courses-list {
    .course-card {
      background: white;
      border-radius: 2.67vw;
      padding: 4vw;
      margin-bottom: 4vw;
      display: flex;
      box-shadow: 0 0.53vw 2.67vw rgba(0, 0, 0, 0.05);
      transition: transform 0.2s ease;

      &:active {
        transform: scale(0.98);
      }

      .course-image {
        width: 25.33vw;
        height: 19.2vw;
        border-radius: 2vw;
        overflow: hidden;
        margin-right: 4vw;
        flex-shrink: 0;

        :deep(.van-image) {
          width: 100%;
          height: 100%;
        }
      }

      .course-content {
        flex: 1;
        display: flex;
        flex-direction: column;

        .course-title {
          font-size: 4.27vw;
          font-weight: 500;
          color: #323233;
          margin-bottom: 1.33vw;
          line-height: 1.4;
        }

        .course-description {
          font-size: 3.73vw;
          color: #646566;
          line-height: 1.5;
          margin-bottom: 2.67vw;
          flex: 1;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }

        .course-meta {
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-size: 3.47vw;
          color: #969799;

          .rating {
            display: flex;
            align-items: center;
            gap: 1.33vw;
          }
        }
      }
    }
  }
}

// 筛选弹窗
.filter-popup {
  padding: 5.33vw;
  background-color: #fff;

  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5.33vw;
    padding-bottom: 4vw;
    border-bottom: 1px solid #ebedf0;

    h3 {
      font-size: 4.8vw;
      font-weight: 600;
      color: #323233;
    }
  }

  .filter-content {
    .filter-group {
      margin-bottom: 6.4vw;

      h4 {
        font-size: 4.27vw;
        font-weight: 500;
        color: #323233;
        margin-bottom: 4vw;
      }

      :deep(.van-checkbox-group),
      :deep(.van-radio-group) {
        display: flex;
        flex-wrap: wrap;
        gap: 2.67vw;
      }

      :deep(.van-checkbox),
      :deep(.van-radio) {
        margin-right: 0;
      }
    }
  }

  .filter-footer {
    padding-top: 5.33vw;
    border-top: 1px solid #ebedf0;
  }
}

// 响应式适配
@media (max-width: 375px) {
  .study-content {
    padding: 3vw;
  }
}

// 空状态样式
.empty-state {
  padding: 8vw 4vw;

  .van-empty__description {
    color: #969799;
    font-size: 3.5vw;
    margin-top: 3vw;
  }

  .bottom-button {
    margin-top: 4vw;
    padding: 0 6vw;
    height: 9vw;
    font-size: 3.5vw;
  }
}

// 加载状态样式
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 12vw 0;

  .van-loading {
    font-size: 3.5vw;
  }
}

// 开发测试按钮样式
.dev-test-buttons {
  display: flex;
  gap: 2vw;
  padding: 4vw;
  background-color: #f7f8fa;
  border-radius: 2vw;
  margin: 4vw 0;

  .van-button {
    flex: 1;
    height: 8vw;
    font-size: 3vw;
  }
}
</style>
